﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AkazoNobel.Scheduler.StoreMasterData.Common;
using AkazoNobel.Scheduler.StoreMasterData.DataAccess.Model;
using Dapper;
using log4net;
using System.Reflection;

namespace AkazoNobel.Scheduler.StoreMasterData.DataAccess.Service
{
    public static class BusinessService
    {
        public static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        
        #region 每次发起小流程自动插入子流程表
        public static void SaveChildProcess(int incident,string process, Assessment ass, string status)
        {
            var childProcess = getChildProcessByPI(incident,process);
            if (childProcess == null)
            {
                childProcess = new t_smd_ChildProcess
                {
                    Incident = incident,
                    Process = process,
                    BusinessProcess = ass.BusinessProcess,
                    BusinessKey = ass.BusinessKey,
                    Status = status
                };
            }
            else
            {
                childProcess.Status = status;
            }

            using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                var trans = conn.BeginTransaction();

                try
                {
                    conn.Execute(
                        "INSERT INTO t_smd_ChildProcess(incident,process,BusinessProcess,BusinessKey,Status) " +
                        "VALUES(@incident,@process,@BusinessProcess,@BusinessKey,@Status)",
                        childProcess, trans);

                    trans.Commit();
                    Logger.Debug("childProcess :" + childProcess.BusinessProcess + " -- " + childProcess.BusinessKey + " " + "成功！");
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Logger.Debug("process"+process+"&incident"+incident+"插入子流程数据失败。");
                    Logger.Error(ex);

                }
            }

           
        }
        #endregion

        #region 获取子流程
        public static t_smd_ChildProcess getChildProcessByPI(int incident ,string process)
        {
            t_smd_ChildProcess childProcess;
            using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                childProcess = conn.Query<t_smd_ChildProcess>("SELECT * FROM t_smd_ChildProcess WHERE process = @process and incident = @incident",
                    new { process,incident}).FirstOrDefault();
            }

            return childProcess;
        }
        #endregion

        #region 插入流程变量
        public static void saveProcessRelation(int incident, string process, Store storemasterdata, Assessment ass, SmdStore store, SmdDevice device, Dealer dealer, Dealer oldDealer, List<SmdStore> stores, List<SmdDevice> devices, List<Dealer> dealers)
        {
            var relation = getRelationByPI(ass.BusinessKey);
            if (relation == null)
            {
                relation = new t_smd_Relation
                {
                    Process = process,
                    Incident = incident,
                    BusinessKey = ass.BusinessKey,
                    BusinessProcess = ass.BusinessProcess,
                };
            }
            relation.EapproveSN = storemasterdata.EapproveSN;
            relation.EapproveData = storemasterdata.StoreApprovedDate.ToString("yyyy-MM-dd");
            if (store != null)
            {
                relation.StoreName = store.StoreName;
                relation.StoreID = store.StoreID.ToString();
                relation.AuthID = store.AuthID;
                relation.City = store.CityName;
                relation.StoreStatus = store.StoreStatus;
                relation.StoreType = store.StoreType;
                relation.Region = store.Region;
                relation.Province = store.Province;
             }

            if (device != null)
            {
                relation.DeviceID = device.DeviceID.ToString();
                relation.FullsetSN = device.FullSetSN;
            }

            if (dealer != null)
            {
                relation.DealerID = dealer.DealerID.ToString();
                relation.DealerCode = dealer.DealerCode;
            }

            if (oldDealer != null)
            {
                relation.OldDealerCode = oldDealer.DealerCode;
                relation.OldDealerID = oldDealer.DealerID;
            }
            if (stores != null && stores.Count > 0)
            {
                var storeName = "";
                var StoreID = "";
                var AuthID = "";
                var EapproveSN = "";
                var EapproveData = "";
                var storeStatus = "";
                var storeType = "";

                for (int i = 0; i < stores.Count; i++)
                {
                    storeName += stores[i].StoreName;
                    StoreID += stores[i].StoreID;
                    AuthID += stores[i].AuthID;
                    storeStatus += stores[i].StoreStatus;
                    storeType += stores[i].StoreType;

                    EapproveSN += stores[i].EapproveSN;
                    EapproveData += stores[i].StoreApprovedDate.HasValue ? stores[i].StoreApprovedDate.Value.ToString("yyyy-MM-dd") : "";

                    if (i < stores.Count - 1)
                    {
                        storeName += ",";
                        StoreID += ",";
                        AuthID += ",";
                        EapproveSN += ",";
                        EapproveData += ",";
                        storeType += ",";
                        storeStatus += ",";
                    }
                }
                relation.StoreName = storeName;
                relation.StoreID = StoreID;
                relation.AuthID = AuthID;
                relation.StoreType = storeType;
                relation.StoreStatus = storeStatus;
                relation.City = stores[0].CityName;
                relation.Region = stores[0].Region;
                relation.Province = stores[0].Province;
                relation.EapproveSN = EapproveSN;
                relation.EapproveData = EapproveData;

            }

            if (dealers != null && dealers.Count > 0)
            {
                var dealerID = "";
                var dealerCode = "";
                List<string> regions = new List<string>();
                List<string> Provinces = new List<string>();
                List<string> Citys = new List<string>();
                for (int i = 0; i < dealers.Count; i++)
                {
                    dealerID += dealers[i].DealerID;
                    dealerCode += dealers[i].DealerCode;
                    regions.Add(dealers[i].Region);
                    Provinces.Add(dealers[i].Province);
                    Citys.Add(dealers[i].CityName);
                    if (i < stores.Count - 1)
                    {
                        dealerID += ",";
                        dealerCode += ",";
                    }
                }
                regions = regions.Distinct().ToList<string>();
                Provinces = Provinces.Distinct().ToList<string>();
                Citys = Citys.Distinct().ToList<string>();
                var region = "";
                var province = "";
                var city = "";
                foreach (var _region in regions)
                {
                    region = string.Join(",", _region);
                }
                foreach (var _province in Provinces)
                {
                    province = string.Join(",", _province);
                }
                foreach (var _city in Citys)
                {
                    city = string.Join(",", _city);
                }

                relation.DealerID = dealerID;
                relation.DealerCode = dealerCode;
                relation.Region = region;
                relation.Province = province;
                relation.City = city;
            }
            using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                var trans = conn.BeginTransaction();

                try
                {
                    conn.Execute(
                        "INSERT INTO t_smd_Relation(BusinessKey,Process,Incident,BusinessProcess,EapproveSN,EapproveData,AuthID,StoreName,StoreStatus,StoreType,OldDealerCode,FullsetSN,Region,Province,City,DealerCode,StoreID,DeviceID,DealerID,OldDealerID) " +
                        "VALUES(@BusinessKey,@Process,@Incident,@BusinessProcess,@EapproveSN,@EapproveData,@AuthID,@StoreName,@StoreStatus,@StoreType,@OldDealerCode,@FullsetSN,@Region,@Province,@City,@DealerCode,@StoreID,@DeviceID,@DealerID,@OldDealerID)",
                        relation, trans);

                    trans.Commit();
                    Logger.Debug("relation :"+relation.BusinessProcess + " -- " + relation.BusinessKey + " " + "成功！");
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Logger.Debug("process" + process + "&incident" + incident + "插入业务数据失败。");
                    Logger.Error(ex);

                }
            }
        }
        #endregion

        #region 获取流程关系
        public static t_smd_Relation getRelationByPI(string processKey)
        {

            t_smd_Relation relation;
            using (var conn = SqlConnectionHelper.GetConnection(Constant.MDC_DB_NAME))
            {
                relation = conn.Query<t_smd_Relation>("SELECT * FROM t_smd_Relation WHERE BusinessKey = @BusinessKey",
                    new { BusinessKey = processKey }).FirstOrDefault();
            }

            return relation;
        }
        #endregion
    }
}
